package com.iyao_app.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.iyao_app.R;
import com.iyao_app.adapter.FindAttentionAdapter;
import com.iyao_app.adapter.PicturesAdapter;
import com.iyao_app.entry.FindBean;
import com.iyao_app.entry.PageInfo;
import com.iyao_app.entry.PreviewData;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.StoryData;
import com.iyao_app.entry.StoryDetail;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.ShareUrl;
import com.iyao_app.im.activity.DiscoverActivity;
import com.iyao_app.mvp.preview.ImageViewPagerActivity;
import com.iyao_app.mvp.signlist.SignMapListActivity;
import com.iyao_app.mvp.storydetail.StoryDetailActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.SpaceItemDecorationFind;
import com.iyao_app.util.ToastUtil;
import com.iyao_app.view.OnImageClickListener;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.PopupWindowUtils;
import com.iyaowoqu.base_library.util.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import github.chenupt.dragtoplayout.AttachUtil;

/**
 * Created by tongxue on 2017/11/30.
 */

public class FindFragment extends Fragment implements OnLoadmoreListener {

    public static final String ARG_PAGE = "ARG_PAGE";
    Unbinder unbinder;
    @BindView(R.id.rv_horizontal)
    RecyclerView rvHorizontal;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.iv_abnormal)
    ImageView mIvAbnormal;
    @BindView(R.id.friend_no)
    TextView mFriendNo;
    private int mPage;
    private FindAttentionAdapter findAttentionAdapter;

    public List<FindBean> model = new ArrayList<>();

    private final int pageSize = 10;
    int page = 1;
    private PageInfo pageInfo;
    private List<StoryDetail> list;

    public static FindFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        FindFragment pageFragment = new FindFragment();
        pageFragment.setArguments(args);
        return pageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = null;
        if (mPage == 1) {
            view = inflater.inflate(R.layout.fragment_find, container, false);
            unbinder = ButterKnife.bind(this, view);
        }
        if (mPage == 2) {
            view = inflater.inflate(R.layout.fragment_find, container, false);
            unbinder = ButterKnife.bind(this, view);
        }
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(MessageEvent event) {
        if (event.getState() == MessageEvent.UPDATE_STORY) {
            StoryDetail message = (StoryDetail) event.getMessage();
            int position = message.position;
            StoryDetail storyDetail = findAttentionAdapter.getData().get(position);
            storyDetail.goodVote = message.goodVote;
            storyDetail.goodCount = message.goodCount;
            storyDetail.commentCount = message.commentCount;
            findAttentionAdapter.notifyItemChanged(position);
        }
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setOnLoadmoreListener(this);
        rvHorizontal.setLayoutManager(new LinearLayoutManager(getActivity()));
        findAttentionAdapter = new FindAttentionAdapter(list, new OnImageClickListener() {
            @Override
            public void onImageClick(List<String> list, int position) {
                PreviewData previewData = new PreviewData();
                previewData.image = list;
                previewData.position = position;
                Intent intent = new Intent(getActivity(), ImageViewPagerActivity.class);
                intent.putExtra(Contants.CLASS_TYPE, previewData);
                startActivity(intent);
            }
        });
        rvHorizontal.setAdapter(findAttentionAdapter);
        rvHorizontal.addItemDecoration(new SpaceItemDecorationFind((int) getActivity().getResources().getDimension(R.dimen.x20)));
        findAttentionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                StoryDetail item = (StoryDetail) adapter.getItem(position);
                Intent intent = new Intent(getActivity(), StoryDetailActivity.class);
                intent.putExtra(Contants.TYPE, item.id);
                item.position = position;
                intent.putExtra(Contants.CLASS_TYPE, item);
                startActivity(intent);
            }
        });
        findAttentionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                StoryDetail item = (StoryDetail) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.tv_like:
                        break;
                    case R.id.tv_comment:
                        item.position = position;
                        Intent intent = new Intent(getActivity(), StoryDetailActivity.class);
                        intent.putExtra(Contants.TYPE, item.id);
                        intent.putExtra(Contants.CLASS_TYPE, item);
                        startActivity(intent);
                        break;
                    case R.id.tv_zhuanfa:
                        zhuanfa();
                        break;
                }
            }
        });

        switch (mPage) {
            case 1:
                getDiscover(true);
                break;
            case 2:
                getattention(true);
                break;
        }
        // attach top listener
        rvHorizontal.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                ((DiscoverActivity) getActivity()).attch(AttachUtil.isRecyclerViewAttach(recyclerView));
            }
        });

    }

    private void zhuanfa() {
        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(getActivity(), R.layout.pop_share, mRefreshLayout)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                .location(Gravity.BOTTOM, 0, Utils.getBottomStatusHeight(getContext()))
                .focuseAble(true)
                .Animation(PopupWindowUtils.ANIMATION_BOTTOM)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {

                        boolean install = UMShareAPI.get(getContext()).isInstall(getActivity(), SHARE_MEDIA.WEIXIN);
                        if (install) {
                            UMImage umImage = new UMImage(getContext(), "https://aiyao-user-image.oss-cn-zhangjiakou.aliyuncs.com/iyao_cms/tb_article/784ba19a94698a7a6b487a7598b1e0bf_1024*1024.jpg");
                            UMWeb web = new UMWeb(ShareUrl.getInstace().signShare(id));
                            web.setTitle("“哎吆我去”邀您来玩");//标题
                            web.setThumb(umImage);  //缩略图
                            web.setDescription("一款好玩儿的交友平台，给你不一样的赶脚！");//描述
                            switch (id) {
                                case R.id.tv_friend:
                                    new ShareAction(getActivity())
                                            .withMedia(web)
                                            .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                            .share();

                                    break;
                                case R.id.tv_weixin:
                                    new ShareAction(getActivity())
                                            .withMedia(web)
                                            .setCallback(umShareListener)
                                            .setPlatform(SHARE_MEDIA.WEIXIN)
                                            .share();
                                    break;
                            }
                        } else {
                            Toast.makeText(getContext(), "请先安装微信客户端", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, R.id.tv_friend, R.id.tv_weixin)
                .show();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            LogUtil.e("plat" + "============" + "platform" + platform);

            Toast.makeText(getContext(), " 分享成功啦", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getContext(), " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                LogUtil.e("throw" + "============" + "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    private void getDiscover(final boolean isRefesh) {
        if (isRefesh) {
            page = 1;
        } else {
            page++;
        }
        NetUtils.getInstance().getEventList(null, null, "2", page, pageSize, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        StoryData storyData = model.getModel();
                        if (storyData != null) {
                            List<StoryDetail> list = storyData.list;
                            pageInfo = storyData.pageInfo;
                            if (pageInfo.pageTotal <= page) {
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (isRefesh) {
                                mRefreshLayout.finishRefresh();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (list == null && list.size() == 0) {
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                if (isRefesh) {
                                    findAttentionAdapter.getData().clear();
                                }
                                findAttentionAdapter.addData(list);
                            }
                        }
                    }

                }
            }

            @Override
            public void onFail(String message, int code) {
                if (isRefesh) {
                    mRefreshLayout.finishRefresh();
                } else {
                    mRefreshLayout.finishLoadmore();
                }
            }
        }, StoryData.class);
    }

    private void getattention(final boolean isRefesh) {

        if (isRefesh) {
            page = 1;
        } else {
            page++;
        }
        NetUtils.getInstance().getEventGetFriendsEvent(DbUtil.getUser().id, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        StoryData storyData = model.getModel();
                        if (storyData != null) {
                            List<StoryDetail> list = storyData.list;
                            pageInfo = storyData.pageInfo;
                            if (pageInfo.pageTotal <= page) {
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (isRefesh) {
                                mRefreshLayout.finishRefresh();
                            } else {
                                mRefreshLayout.finishLoadmore();
                            }
                            if (list == null && list.size() == 0) {
                                mRefreshLayout.finishLoadmoreWithNoMoreData();
                            } else {
                                if (isRefesh) {
                                    findAttentionAdapter.getData().clear();
                                }
                                findAttentionAdapter.addData(list);
                            }
                        }
                    }
                } else if (code == 50400) {
                    mFriendNo.setVisibility(View.VISIBLE);
                    mIvAbnormal.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFail(String message, int code) {
                if (isRefesh) {
                    mRefreshLayout.finishRefresh();
                } else {
                    mRefreshLayout.finishLoadmore();
                }
            }
        }, StoryData.class);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        switch (mPage) {
            case 1:
                getDiscover(false);
                break;
            case 2:
                getattention(false);
                break;
        }
    }

}